//------------------------------------------------------------------------------
//SFWK Framework
//Copyright (C) 2011 SQLI

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------

using System;
using System.IO;
using System.Xml;
using System.Runtime.Serialization;

namespace SFWK.Core
{
    /// <summary>
    /// Provides methods to serialize DataContract objects
    /// </summary>
    public static class SerializeHelper
    {
        public static string SerializeXml(object value)
        {
            if (value.GetType() == typeof(string))
                return value.ToString();

            StringWriter stringWriter = new StringWriter();
            using (XmlWriter writer = XmlWriter.Create(stringWriter))
            {
                DataContractSerializer serializer = new
                  DataContractSerializer(value.GetType());
                serializer.WriteObject(writer, value);
            }

            return stringWriter.ToString();
        }
        public static object DeserializeXMl(Type type, string serializedValue)
        {
            if (type == typeof(string))
                return serializedValue;

            using (StringReader stringReader = new StringReader(serializedValue))
            {
                using (XmlReader reader = XmlReader.Create(stringReader))
                {
                    DataContractSerializer serializer =
                     new DataContractSerializer((type));

                    object deserializedValue = serializer.ReadObject(reader);

                    return deserializedValue;
                }
            }
        } 
 

    }
}

